<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{ room }} 消息互动 管理后台</title>
    <link href="{{url_for('static', filename='css/bootstrap.min.css')}}" rel="stylesheet">
    <script src="{{url_for('static', filename='js/jquery-3.6.0.min.js')}}"></script>
    <script src="{{url_for('static', filename='js/mqttws31.js')}}" type="text/javascript"></script>  
</head>
<body>
    <div class="container">
        <div class="card mt-5">
            <div class="card-header">
                <h1 class="text-center">{{ room }} 消息 管理后台</h1>
            </div>
            <div id="connected_mqtt" class="alert alert-success text-center" role="alert"></div>
            <div class="card-body">
                <div class="row">
                <div class="col-md-6">
                    <div class="border border-primary rounded-3 p-3 bg-light">
                        <h5>收到的消息：</h5>
                        <div>
                            <ol id="messages" class="list-group mt-3"></ol>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <form>
                        <div class="mb-3">
                            <label for="pcid" class="form-label">回复 座位号：</label>
                            <input type="text" class="form-control" id="pcid">
                        </div>
                        <div class="mb-3">
                            <label for="reply" class="form-label">回复内容：</label>
                            <textarea class="form-control" id="reply" name="reply" rows="3"></textarea>
                        </div>
                        <input type="button" class="btn btn-primary" value="发送" onclick="send_reply()">
                    </form>

                    <hr class="border border-primary border-2 opacity-50">
                    <h5>回复历史：</h5>
                    <div>
                        <ol id="answers" class="list-group mt-3"></ol>
                    </div>
                </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        room = "{{ room }}"

        // MQTT broker 配置
        var MQTT_BROKER = "{{ mqtt_account['MQTT_BROKER'] }}";
        var MQTT_PORT = Number("{{ mqtt_account['MQTT_PORT'] }}");

        // MQTT client
        var mqtt_client = new Paho.MQTT.Client(MQTT_BROKER, MQTT_PORT, "admin_" + Math.random().toString(16).substr(2, 8));

        // 连接 MQTT broker
        mqtt_client.connect({
            onSuccess: function() {
                console.log("Connected to MQTT broker");
                document.getElementById("connected_mqtt").innerHTML= "连接 MQTT broker 成功！";
                //mqtt_client.subscribe("messages/1")

                // 订阅接收的消息，主题样式："messages_room1/1"
                mqtt_client.subscribe("messages_" + room + "/+", {
                    onSuccess: function() {
                        console.log("Subscribed to incoming messages");
                    },
                    onFailure: function() {
                        console.log("Failed to subscribe to incoming messages");
                    }
                });
            },
            onFailure: function() {
                console.log("Failed to connect to MQTT broker");
                document.getElementById("connected_mqtt").innerHTML= "连接 MQTT broker 失败!";
            }
        });

        // 处理接收到 的 MQTT 回复消息
        mqtt_client.onMessageArrived = function(message) {
            console.log("Message received on topic " + message.destinationName + " with payload " + message.payloadString);

            // 从主题（topic）中截取 computer_id
            var computer_id = message.destinationName.split("/")[1];

            // 在页面上显示问题消息
            var messagesDiv = document.getElementById("messages");
            messagesDiv.innerHTML += '<li class="list-group-item">' + message.payloadString + "</li>";

            //document.getElementById("messages").value = message.payloadString;

            // Process incoming message
            //var reply = "Message received and processed";

            // Publish reply to MQTT broker
            //mqtt_client.send("replies/" + computer_id, reply);
        };

        // 发送回复消息
        function send_reply() {
            // Get computer ID and message
            var computer_id = document.getElementById("pcid").value;
            var answersDiv = document.getElementById("answers");
            var message = document.getElementById("reply").value;
            answersDiv.innerHTML += '<li class="list-group-item">' + "回复" + computer_id + ": " + message + "</li>";

            // 发送回复消息 to MQTT broker
            mqtt_client.send("replies_" + room + "/" + computer_id, message);
            //mqtt_client.send("replies_room1/1", message);
        }
    </script>
</body>
</html>
